package com.snopy.concurrency.demo_threadpool;

import lombok.extern.slf4j.Slf4j;

import java.sql.Time;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author snopy
 * @version 1.0.0
 * @classname SynchronousQueueTest
 * @description
 * @email 77912204@qq.com
 * @date 2022/02/19 13:42
 */
@Slf4j
public class SynchronousQueueTest {
    //private static final ThreadPoolExecutor tpe = new ThreadPoolExecutor(2,3,5, TimeUnit.SECONDS,new SynchronousQueue<>(true));
    private static final SynchronousQueue<Banana> sq = new SynchronousQueue<>(true);
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Producer(sq));
        Thread thread2 = new Thread(new Producer(sq));
        Thread thread3 = new Thread(new Consumer(sq));
        Thread thread4 = new Thread(new Consumer(sq));
        thread1.start();
        //thread2.start();
        thread3.start();
        //thread4.start();
        while (true){
            try {
                TimeUnit.SECONDS.sleep(1);
                log.info("线程thread1状态->{}线程thread2状态->{}线程thread3状态->{}线程thread4状态->{}",thread1.getState(),thread2.getState(),thread3.getState(),thread4.getState());

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
            //new Thread(new Consumer(sq)).start();
    }

    static class Banana{
        Banana(){

        }
    }
    static class Producer implements Runnable{

        SynchronousQueue<Banana> sq;
        Producer(SynchronousQueue<Banana> sq){
            this.sq = sq;
        }
        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                    produce();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        private synchronized void produce(){
            Banana banana = new Banana();
            try {
                sq.put(banana);
                log.info("长出了一个banana->{}",banana);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    static class Consumer implements Runnable{

        SynchronousQueue<Banana> sq;
        Consumer(SynchronousQueue<Banana> sq){
            this.sq = sq;
        }
        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(1);
                    consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        private void consume(){
            try {
                Banana take = sq.take();
                log.info("买下一个banana->{}",take);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
